import Vue from 'vue';
import {
    url,
} from '@/lib/utils';
import {
    api,
} from '@/lib/api';
import ProductModel from '@/lib/models/product';

import { Module } from 'vuex';
import { RootState } from '@/types/store';
import store from '.';

export interface GoodState {
    // 商城左侧滑动菜单栏
    sliderList:{
        [status: string]: ListWrap<Product.Slider> & ListReq;
    };
    getParams:{
        [status: string]: ListWrap<Product.Slider> & ListReq;
    }
    productList: {
        [shopId_category_sort_screen_name: string]: ListWrap<number> & ListReq;
    };
    // 门店商品列表
    lists: {
        [shopId_category_first_category_id_sort_screen_name: string]: ListWrap<number> & ListReq;
    };
    listsMap: {
        [listsId: number]: Product.ListItem;
    },
    productMap: {
        [productId: number]: Product.ListItem;
    };
    productDetailMap: {
        [productId: number]: ProductModel;
    };
    /** 评价 */
    comments: {
        [productId: number]: ListWrap<Product.Comment> & ListReq;
    };
    /** 评价数量 count, favorable */
    commentCount: {
        [productId: number]: number;
    };
    /** 规格信息 */
    spec: {
        [specId: number]: Product.Spec;
    };
    posterMap: {
        [productId: number]: string;
    };
    /** 返利规则 */
    rebateRule: {
        [productId_specId: string]: Product.RebateRule[];
    };
    discount: {
        [goodId: number]: {
            full_reduction: Product.FullReductionDiscount[];
            discount: Product.DiscountDiscount[];
            gift: Product.GiftDiscount[];
            balance:{}
            // balance: Product.BalanceDiscount[];
        };
    };
    brand: {
        [parent: string]: IdName[];
    };
    // 商城筛选分类
    getparentType: string;
    // 顶级分类id
    getTopCategoryid:string;
    topAllCategory: [];
    checkUser: any;
}

const m: Module<GoodState, RootState> = {
    namespaced: true,
    state: {
        sliderList:{},
        getParams:{},

        productList: {},
        lists:{},
        listsMap:{},
        productMap: {},
        productDetailMap: {},
        /** 评价 */
        comments: {},
        /** 评价数量 count, favorable */
        commentCount: {},
        /** 规格信息 */
        spec: {},
        posterMap: {},
        /** 返利规则 */
        rebateRule: {},
        discount: {
        },
        brand: {},
        getparentType: '',
        getTopCategoryid:'',
        topAllCategory: [],
        checkUser: false,
    },
    mutations: {
        setgetparentType(state, data){
            state.getparentType = data;
        },
        setTopCategoryid(state, data){
            state.getTopCategoryid = data;
        },
        // 
        getSliderList(state, data){
            state.sliderList = data;
        },
        setGetParams(state, data){
            state.getParams = data;
        },

        /**
         * 设置普通商品列表
         */
        initProductList(state, key) {
            
            Vue.set(state.productList, key, {
                list: [],
                req: false,
                loaded: false,
            });
        },
        setProductListReq(state, { key, req }) {
            state.productList[key].req = req;
        },
        setProductListLoaded(state, { key, loaded }) {
            state.productList[key].loaded = loaded;
        },
        concatProductList(state, { key, list }) {
            const idList = state.productList[key].list;
            list.forEach((item) => {
                idList.push(item.id);
                Vue.set(state.productMap, item.id, item);
            });
            Vue.set(state.productList[key], 'list', idList);
        },
        /**
         * 设置门店商品列表
         */
        initlists(state, key) {
            Vue.set(state.lists, key, {
                list: [],
                req: false,
                loaded: false,
            });
        },
        setlistsReq(state, { key, req }) {
            state.lists[key].req = req;
        },
        setlistsLoaded(state, { key, loaded }) {
            state.lists[key].loaded = loaded;
        },
        concatlists(state, { key, list }) {
            const idList = state.lists[key].list;
            list.forEach((item) => {
                idList.push(item.id);
                Vue.set(state.listsMap, item.id, item);
            });
            Vue.set(state.lists[key], 'list', idList);
        },
        /**
         * 记录详情
         */
        setProductDetail(state, { productId, detail }: { productId: number; detail: Product.Detail }) {
            const product = new ProductModel();
            product.loadRaw(detail);

            Vue.set(state.productDetailMap, productId, product);
            for (const spec of detail.spec) {
                Vue.set(state.spec, spec.id, { ...spec });
            }
        },
        /**
         * 评论列表
         */
        initComments(state, productId) {
            Vue.set(state.comments, productId, {
                list: [],
                loaded: false,
                req: false,
            });
        },
        concatComments(state, { productId, list }) {
            state.comments[productId].list.push(...list);
        },
        setCommentsLoaded(state, { productId, loaded }) {
            state.comments[productId].loaded = loaded;
        },
        setCommentsReq(state, { productId, req }) {
            state.comments[productId].req = req;
        },
        /**
         * 记录评价数量信息
         */
        setCommentCount(state, { productId, commentCount }) {
            Vue.set(state.commentCount, productId, commentCount);
        },
        /** 记录分享海报 */
        setPoster(state, { productId, poster }) {
            Vue.set(state.posterMap, productId, poster);
        },
        /** 记录返利规则 */
        setRebateRule(state, { key, list, }) {
            Vue.set(state.rebateRule, key, list);
        },
        /**
         * 记录优惠信息
         */
        setDiscount(state, { goodId, detail }) {
            Vue.set(state.discount, goodId, detail);
        },
        /**
         * 记录品牌信息
         */
        setBrand(state, { parent, brand }) {
            Vue.set(state.brand, parent, brand);
        },
        // 存储顶级分类下的所有筛选参数
        setTopAllCategory(state,data){
            state.topAllCategory = data;
        },
        setCheckUser(state, data) {
            state.checkUser = data;
       }
    },

    actions: {
        /**
         * 获取商城左滑菜单
         */
        async getSliderList({ state, commit }, { pid, is_view_show }) {
            const key = `${pid}_${is_view_show}`;
            const response = await api.get({
                url: `${url}/api/category`,
                data: {
                    pid: pid,
                    is_view_show: is_view_show,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                commit('getSliderList',rdata.data);
            }
            return rdata;
        },
        // 获取筛选内容
        async getParams({ state, commit }, { shop_id }) {
            const response = await api.get({
                url: `${url}/api/shop/params`,
                data: {
                    shop_id: shop_id
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                commit('setGetParams',rdata.data);
            }
            return rdata;
        },

        /**
         * 获取普通类商品列表
         */
        // brand = null, shopId = null, category = null, SpecName = null, offset, count, sort = null, screen = null, name = null, forceUpdate
        async getProductList({ state, commit }, { brand = '', shopId = null, category = '', SpecName = '', offset, count, sort = null, screen = null, name = null, forceUpdate}) {
            const key = `${brand}_${shopId}_${category}_${SpecName}_${sort}_${JSON.stringify(screen)}_${name}`;
            if (forceUpdate || !state.productList[key]) {
                commit('initProductList', key);
            }
            const wrap = state.productList[key];
            const length = wrap.list.length;
            const end = offset + count;
            if (wrap.loaded || wrap.req) {
                return;
            }
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - length;
            }
            commit('setProductListReq', { key, req: true });
            const res = await api.post({
                url: `${url}/api/good`,
                data: {
                    brand_id: brand,
                    shop_id: shopId,
                    category: category,
                    // category_id: categoryId,    
                    category_id: SpecName,    
                    offset,
                    count,
                    sort: sort,
                    screen: screen,
                    name,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatProductList', {
                    key,
                    list,
                });

                if (list.length < count) {
                    commit('setProductListLoaded', {
                        key,
                        loaded: true,
                    });
                }
                
            }
            commit('setProductListReq', { key, req: false });
            // 设置筛选分类
            if(res.data.data != [] && res.data.data.length != "0"){
                for(var i=0;i < res.data.data.length;i++){
                    if(res.data.data[i].top_category_id != null && res.data.data[i].top_category_id){
                        commit('setgetparentType', res.data.data[i].category);
                        commit('setTopCategoryid', res.data.data[i].top_category_id);
                        break;
                    }
                }

            }else{
                commit('setgetparentType', '')
                commit('setTopCategoryid', '');
            }
            
            return res;
        },
        /**
         * 获取门店商品列表
         */
        
        async getlists({ state, commit }, { brand = '', shopId = null, category = null, SpecName = null, categoryId = null, first_category_id = null, offset, count, sort = null, screen = null, name = null, forceUpdate}) {
            const key = `${brand}_${shopId}__${SpecName}_${first_category_id}_${sort}_${JSON.stringify(screen)}_${name}`;
            if (forceUpdate || !state.lists[key]) {
                commit('initlists', key);
            }
            const wrap = state.lists[key];
            const length = wrap.list.length;
            const end = offset + count;
            if (wrap.loaded || wrap.req) {
                return;
            }
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - length;
            }
            commit('setlistsReq', { key, req: true });
            const res = await api.post({
                url: `${url}/api/good/lists`,
                data: {
                    brand_id: brand,
                    shop_id: shopId,
                    category: category,
                    // category_id: categoryId,
                    category_id: SpecName,
                    first_category_id:first_category_id, 
                    offset,
                    count,
                    sort: sort,
                    screen: screen,
                    name,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatlists', {
                    key,
                    list,
                });
                if (list.length < count) {
                    commit('setlistsLoaded', {
                        key,
                        loaded: true,
                    });
                }
            }
            commit('setlistsReq', { key, req: false });
            return res;
        },
        /**
         * 获得详情
         */
        async getDetail(context, { productId, forceUpdate }) {
            if (context.state.productDetailMap[productId] && !forceUpdate) {
                return;
            }
            const response = await api.get({
                url: `${url}/api/good/detail`,
                data: {
                    id: productId,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                rdata.data.id = productId;
                context.commit('setProductDetail', {
                    productId,
                    detail: rdata.data,
                });
            }
            return response;
        },
        /**
         * 获取普通类商品列表
         */
        async getComments({ state, commit }, { productId, offset, count, forceUpdate }) {
            let wrap = state.comments[productId];
            if (!wrap) {
                commit('initComments', productId);
                wrap = state.comments[productId];
            }
            if (wrap.loaded || wrap.req) {
                return;
            }

            const length = wrap.list.length;
            const end = offset + count;
            if (end <= length) {
                return;
            }
            if (offset < length) {
                offset = length;
                count = end - length;
            }
            commit('setCommentsReq', { productId, req: true });
            const res = await api.get({
                url: `${url}/api/good/comment`,
                data: {
                    id: productId,
                    offset,
                    count,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                const list = res.data.data;
                commit('concatComments', {
                    productId,
                    list,
                });
                if (list.length < count) {
                    commit('setCommentsLoaded', {
                        productId,
                        loaded: true,
                    });
                }
            }
            commit('setCommentsReq', { productId, req: false });
            return res;
        },
        /**
         * 获取评价数量
         */
        async getCommentCount(context, { productId }) {
            const res = await api.get({
                url: `${url}/api/good/comment_count`,
                data: {
                    id: productId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                context.commit('setCommentCount', {
                    productId,
                    commentCount: res.data.data,
                });
            }
            return res;
        },
        /** 添加访问量 */
        async addVisitor({ state, commit }, { id }) {
            const res = await api.get({
                url: `${url}/api/good/visitor`,
                data: {
                    id,
                },
            });
            return res;
        },
        /** 添加分享量 */
        async addShare({ state, commit }, { id }) {
            const res = await api.get({
                url: `${url}/api/good/share`,
                data: {
                    id,
                },
            });
            return res;
        },
        /** 获取海报 */
        async getGoodPoster({ state, commit }, { productId }) {
            if (state.posterMap[productId]) {
                return;
            }
            const res = await api.get({
                url: `${url}/api/good/poster`,
                data: {
                    id: productId,
                },
            });
            if (res.statusCode === 200 && res.data.status === 0) {
                commit('setPoster', {
                    productId,
                    poster: res.data.data,
                });
            }
            return res;
        },
        /**
         * 获取返利规则
         */
        async getRebateRule(context, { productId, specId, }) {
            const response = await api.get({
                url: `${url}/api/good/rebate_rule`,
                data: {
                    id: productId,
                    spec_id: specId,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                context.commit('setRebateRule', {
                    key: [ productId, specId, ].join('_'),
                    list: rdata.data,
                });
            }
            return rdata;
        },
        /**
         * 获取优惠信息
         */
        async getDiscount(context, { goodId, referrer }) {
            const response = await api.get({
                url: `${url}/api/good/discount`,
                data: {
                    id: goodId,
                    share_user_id: referrer,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                context.commit('setDiscount', {
                    goodId,
                    detail: rdata.data,
                });
            }
            return rdata;
        },
        /**
         * 获取优惠信息
         */
         async getBrand(context, { parent = '' } = {}) {
            const response = await api.get({
                url: `${url}/api/good/brand`,
                data: {
                    parent,
                    offset: 0,
                    count: 1000,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                context.commit('setBrand', {
                    parent,
                    brand: rdata.data,
                });
            }
            return rdata;
        },
        //获取一级分类下的规格
        async getFirstCategorySpec({ state, commit }, { first_category_id,top_category_id, forceUpdate}){
            const response = await api.get({
                url: `${url}/api/query_category`,
                data: {
                    top_category_id:top_category_id,
                    first_category_id:first_category_id,
                    offset: 0,
                    count: 1000,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                var specList = rdata.data;
                var alldata = store.state.good.topAllCategory[1].data;
                for(var t in  alldata){
                    store.state.good.topAllCategory[1].data[t].flag = '';
                }
                for(var i in  alldata){
                    for(var j=0;j<specList.length;j++){
                        if(alldata[i].name == specList[j].name){
                            store.state.good.topAllCategory[1].data[i].flag = true;
                        }
                    }
                }
            }
            return rdata;
        },
        //获取门店下一级分类下的规格
        async getShopFirstCategorySpec({ state, commit }, { first_category_id,top_category_id, forceUpdate}){
            const response = await api.get({
                url: `${url}/api/query_category`,
                data: {
                    top_category_id:top_category_id,
                    first_category_id:first_category_id,
                    offset: 0,
                    count: 1000,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                var specList = rdata.data;
                var alldata = store.state.good.getParams[1].data;
                for(var t in  alldata){
                    store.state.good.getParams[1].data[t].flag = '';
                }
                for(var i in  alldata){
                    for(var j=0;j<specList.length;j++){
                        if(alldata[i].name == specList[j].name){
                            store.state.good.getParams[1].data[i].flag = true;
                        }
                    }
                }
            }
            return rdata;
        },
        //获取顶级分类下所有筛选参数
        async getTopAllCategory({ state, commit }, { top_category_id, forceUpdate}){
            const response = await api.get({
                url: `${url}/api/query_params`,
                data: {
                    top_category_id:top_category_id,
                    offset: 0,
                    count: 1000,
                },
            });
            const rdata = response.data;
            if (response.statusCode === 200 && rdata.status === 0) {
                commit('setTopAllCategory', rdata.data);
            }
            return rdata;
        },
        /**
		 * 查询是否所属集团
		 */
		async getCheckUser(context, { user_id, shop_id }) {
			const response = await api.get({
				url: `${url}/api/good/check_user`,
				data: {
					user_id,
					shop_id,
				},
			});
			const rdata = response.data;
			if (response.statusCode === 200 && rdata.status === 0) {
				context.commit("setCheckUser", rdata.data);
			}
			return rdata;
		},
    },
};

export default m;
